<template>
  <div class="admin-users">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="handleAddUser">
            添加用户
          </el-button>
        </div>
      </template>
      
      <!-- 搜索筛选 -->
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="filters.keyword"
              placeholder="搜索姓名或学号"
              @keyup.enter="loadUsers"
            />
          </el-col>
          <el-col :span="6">
            <el-select v-model="filters.schoolId" placeholder="选择学校" clearable>
              <el-option
                v-for="school in schools"
                :key="school.id"
                :label="school.name"
                :value="school.id"
              />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="filters.status" placeholder="用户状态" clearable>
              <el-option label="正常" :value="1" />
              <el-option label="限制" :value="0" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="loadUsers">搜索</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 用户列表 -->
      <el-table :data="users" v-loading="loading">
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="studentId" label="学号" />
        <el-table-column prop="schoolName" label="学校" />
        <el-table-column prop="major" label="专业" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="balance" label="余额">
          <template #default="{ row }">
            ¥{{ row.balance || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '限制' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="150" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="viewUser(row)">查看</el-button>
            <el-button size="small" type="primary" @click="editUser(row)">编辑</el-button>
            <el-button
              size="small"
              :type="row.status === 1 ? 'danger' : 'success'"
              @click="toggleUserStatus(row)"
            >
              {{ row.status === 1 ? '限制' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination" v-if="users.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadUsers"
          @current-change="loadUsers"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../../utils/api'

const loading = ref(false)
const users = ref([])
const schools = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

const filters = reactive({
  keyword: '',
  schoolId: '',
  status: ''
})

const loadUsers = async () => {
  loading.value = true
  try {
    const response = await api.get('/admin/users')
    if (response.data.code === 200) {
      users.value = response.data.data
      total.value = response.data.data.length
    }
  } catch (error) {
    ElMessage.error('加载用户失败')
  } finally {
    loading.value = false
  }
}

const loadSchools = async () => {
  try {
    const response = await api.get('/auth/schools')
    if (response.data.code === 200) {
      schools.value = response.data.data
    }
  } catch (error) {
    console.error('加载学校列表失败:', error)
  }
}

const resetFilters = () => {
  filters.keyword = ''
  filters.schoolId = ''
  filters.status = ''
  loadUsers()
}

const handleAddUser = () => {
  ElMessage.info('添加用户功能开发中...')
}

const viewUser = (user) => {
  ElMessage.info('查看用户详情功能开发中...')
}

const editUser = (user) => {
  ElMessage.info('编辑用户功能开发中...')
}

const toggleUserStatus = async (user) => {
  try {
    const action = user.status === 1 ? '限制' : '启用'
    await ElMessageBox.confirm(`确定要${action}用户 ${user.name} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里应该调用API更新用户状态
    user.status = user.status === 1 ? 0 : 1
    ElMessage.success(`${action}成功`)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

onMounted(() => {
  loadUsers()
  loadSchools()
})
</script>

<style scoped>
.admin-users {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
